//
//  ApprovalDetailViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/7/12.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

import UIKit

class ApprovalDetailViewController: BaseViewController,UIPageViewControllerDelegate,UIPageViewControllerDataSource,ChangePage {
    
    func change(toPage idx: Int) {
        
        if let vc = page.viewControllers?[0] {
            
            if let currentIndex = ctls.index(of: vc) {
                
                if currentIndex < idx {
                    
                     page.setViewControllers([ctls[idx]], direction: .forward, animated: true, completion: nil)
                    
                } else {
                    page.setViewControllers([ctls[idx]], direction: .reverse, animated: true, completion: nil)
                }
                
            }
        }
    }
    
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx > 0 {
                
                return ctls[idx - 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
        
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        
        if let idx = ctls.index(of: viewController) {
            
            if idx < ctls.count - 1 {
                
                return ctls[idx + 1]
                
            } else {
                
                return nil
                
            }
        }
        
        return nil
    }
    
    func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
        if completed {
            
            let vc = pageViewController.viewControllers![0]
            
            if let index = ctls.index(of: vc) {
                
                slide.slide(toPosition: index)
                
            }
            
        }
    }
    
    
    var applyid = ""
    
    var applyType = ""
    
    var ctls: Array<UIViewController> = []
    
    let page = UIPageViewController.init(transitionStyle: .scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal, options: nil)
    
    let slide = SlidePageView.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 55)))
    
    let approvalBtn = UIButton(type: .system)
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        for view in page.view.subviews {
            if view is UIScrollView {
                let scroll = view as! UIScrollView
                scroll.bounces = false
            }
        }
        
        approvalBtn.setTitle("审批意见", for: .normal)

        approvalBtn.setTitleColor(UIColor.white, for: .normal)

        approvalBtn.backgroundColor = UIColor.mainColor

        approvalBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17)

        approvalBtn.addTarget(self, action: #selector(approvalAction(_:)), for: .touchUpInside)
        self.view.addSubview(approvalBtn)
        
        page.delegate = self
        
        page.dataSource = self
        
        slide.delegate = self
        
        slide.backgroundColor = UIColor.white
        
        self.view.addSubview(slide)
        
        page.view.backgroundColor = UIColor.white
        
        self.view.addSubview(page.view)
        
        for view in page.view.subviews {
            if let scroll = view as? UIScrollView {
                
                scroll.delegate = slide
                
            }
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(refreshBtn), name: NSNotification.Name("RefreshDetail"), object: nil)
        
        self.load(with: "detail")
    }
    
    @objc func refreshBtn()->Void{
//        self.load(with: "detail")
        self.popobjc()
    }
    
    
    @objc func approvalAction(_ : UIButton) -> Void {
        let approval = ApprovalSuggestionViewController()
        approval.applyId = self.applyid
        
        approval.businessType = self.applyType
        
         self.navigationController?.present(vc: approval)
        
    }
    
    override func viewWillLayoutSubviews() {
        
        super.viewWillLayoutSubviews()
        
        slide.width = self.view.width
        
        approvalBtn.frame = CGRect(origin: CGPoint(x: 0.0, y: self.view.height - 55), size: CGSize(width: self.view.width, height: 55))
        
        page.view.frame = CGRect(origin: CGPoint(x: 0, y: slide.bottom), size: CGSize(width: self.view.width, height: self.view.height - slide.height - approvalBtn.height))
        
    }
    
    
    override var names: Array<String> {
        get{
            return ["detail","refresh"]
        }
    }
    
    override func success(for name: String) -> NetSuccess{
        
        func suc(json: JSON)->Void{
            
            print(json)
            
            if json.contents?["success"]?.bool == false {
                self.alert(json.contents?["errorMsg"]?.rawString())
                self.pop()
                return
            }
            
            slide.configTitles(["采购信息","审批记录"])
            
//            guard let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool else {
//
//            }
            if let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool {
                if canoperate == true {
                    approvalBtn.isEnabled = true
                } else {
                    approvalBtn.isEnabled = false
                }
            }
            
            let data = json.contents?["data"]?.contents
            
//            print(data ?? ["":JSON()])
            
            let details = data?["details"]
            let purchase = PurchaseTableViewController()
            
            var contents: Array<Dictionary<String,String?>> = []
            
            contents.append(["采购单号:":details?["serialNumber"].rawString()])
            
            if let type = details?["type"].rawString() {
                
                if type == "serviceEngineering" {
                    contents.append(["采购类型":"服务类"])
                } else if type == "humanResources" {
                    contents.append(["采购类型":"人力类"])
                } else if type == "engineering" {
                    contents.append(["采购类型":"工程类"])
                } else if type == "material" {
                    contents.append(["采购类型":"物资类"])
                }
                
            } else {
                contents.append(["采购类型":"未知"])
            }
            
            contents.append(["任务名称:":details?["taskName"].rawString()])
            
            contents.append(["需求日期:":details?["demandTime"].rawString()])
            
            contents.append(["采购依据:":details?["purchaseBasisName"].rawString()])
            
            if let amount = details?["estimatedAmount"].rawValue as? Int {
                
                let rmb = amount / 100
                
                contents.append(["预算金额(元):":String(rmb).rmbformat])
                
                contents.append(["估算金额(元):":String(rmb).rmbformat])
                
            } else {
                
                contents.append(["预算金额(元):":""])
                
                contents.append(["估算金额(元):":""])
            }
            
            if let ifFrame = details?["whetherFrame"].bool {
                if ifFrame == true {
                    contents.append(["是否框架:":"是"])
                } else {
                    contents.append(["是否框架:":"否"])
                }
            } else {
                contents.append(["是否框架:":"否"])
            }
            
            contents.append(["建议采购方式:":details?["procurementMethod"].rawString()])
            
            contents.append(["暂定包数:":details?["provisionalPacketNumber"].rawString()])
            
            contents.append(["付款方式:":details?["paymentMethod"].rawString()])
            
            let income = details?["incomingAmount"].int ?? 0
            contents.append(["进项金额(元):":String(income / 100).rmbformat])
            
            contents.append(["质保期(月):":details?["warrantyPeriod"].rawString()])
            
            contents.append(["专用资质条件:":details?["qualificationConditions"].rawString()])
            
            contents.append(["服务期限:":details?["servicePeriod"].rawString()])
            
            purchase.source = contents
            
            var attachs: Array<JSON> = []
            
            guard let attachments = details?["attachFiles"].array else {
                return
            }
            for item in attachments {
                attachs.append(item)
            }
            
            purchase.documents = attachs
            
            ctls.append(purchase)
            
            self.page.setViewControllers([purchase], direction: .forward, animated: false, completion: nil)
            
            let type = details?["type"].rawString()
            
            if type != "humanResources" {
                //3ge标签
                
                slide.configTitles(["采购信息","项目信息","审批记录"])
                
                let projectInfo = ProjectInfoViewController.init()
                
                var contents: Array<Dictionary<String,String?>> = []
                
                contents.append(["关联项目:":details?["projectName"].rawString()])
                
                contents.append(["项目编号:":details?["proSerialNumber"].rawString()])
                
                contents.append(["项目负责人:":details?["projManagerName"].rawString()])
                
                let applicantInfo = details?["applicantInfo"].contents
                
                contents.append(["联系电话:":applicantInfo?["phone"]?.rawString()])
                
                contents.append(["申请部门:":applicantInfo?["orgName"]?.rawString()])
                
                contents.append(["项目背景:":applicantInfo?["projectBackground"]?.rawString()])
                
                projectInfo.source = contents
                
                ctls.append(projectInfo)
                
            }
            
            let approvalList = ApprovalRecordListViewController()
            
            if let list = data?["approvalProcess"]?.array {
                
                approvalList.source = list
                
            }
            
            approvalList.tableView.reloadData()
            
            ctls.append(approvalList)
        }
        
        func refresh(json: JSON)->Void{
//            guard let canoperate = json.contents?["data"]?.contents?["operation"]?.rawValue as? Bool else {
//                return
//            }
            
//            if canoperate == true {
//                approvalBtn.isEnabled = true
//            } else {
//                approvalBtn.isEnabled = false
//            }
            
            var approvalList = self.ctls[1] as? ApprovalRecordListViewController
            
            if approvalList != nil {
                
                let data = json.contents?["data"]?.contents
                
                if let list = data?["approvalList"]?.array {
                    
                    approvalList!.source = list
                    
                    approvalList!.tableView.reloadData()
                }
            } else {
                if self.ctls.count > 2 {
                    
                    approvalList = self.ctls[2] as? ApprovalRecordListViewController
                    
                    if approvalList != nil {
                        
                        let data = json.contents?["data"]?.contents
                        
                        if let list = data?["approvalList"]?.array {
                            
                            approvalList!.source = list
                            
                            approvalList!.tableView.reloadData()
                        }
                    }
                    
                }
            }
        }
        
        return name == "detail" ? suc : refresh
        
    }
    
    override func param(for name: String) -> Dictionary<String,Any>{
        return ["applyId":self.applyid,"businessType": "10"]
//        return ["applyId":self.applyid,"businessType":self.applyType]
    }
    
    override func path(for name: String) -> String{
        return PurchaseDetail
//        return "purchasingManage/mobile/sys/approvalprocess/getDetailsByBusinessType"
    }
    
    override func method(for name: String) -> NetMethod{
        return .get
    }
    
}
